# --**coding:utf-8**--
# 设备驱动

import uiautomator2 as u2
import xml.dom.minidom as xml_tool
import xmltodict
import json
import os
import re
import utils

class Driver:

    def __init__(self):
        self.device = u2.content('')
        self.page_activity_name = ''
        self.u = utils
        self.new_activity = []

    def getNewActivity(self):
        return self.new_activity

    def getPageActivityName(self):
        return self.page_activity_name

    def getPageLayout(self):
        # 返回当前页面的布局文件树，dict格式
        layout = self.device.dump_hierarchy(compressed=False, pretty=False)
        xml = xml_tool.parseString(layout)
        xml_pretty_str = xml.toprettyxml()
        # 转换为 dict
        xmlparse = xmltodict.parse(xml_pretty_str)
        json_layout = json.dumps(xmlparse,indent=1)
        dict_layout = json.loads(json_layout)
        # 仅在获取整个页面元素时，记录一次页面的 activity name
        activity_info:dict = self.getPageActivityName()
        if activity_info:
            self.page_activity_name = activity_info.get('activity')
        return dict_layout


    def getActivityName(self):
        # 返回当前页面的activiity name
        result = os.popen('uiautomator2 current').read()
        json_result = json.loads(str(result))
        activity_info = dict(json_result)
        if 'activity' in activity_info.keys():
            return activity_info
        else:
            return None

    def getElementBNounds(self,item: dict):
        '''
        解析元素获取定位
        :param item: 元素信息
        :return: bounds
        '''
        keys = item.keys()
        key = '@bounds'
        if key in keys:
            bounds:str = item.get(key)
            if not bounds.startswith('[') or not bounds.endswith(']'):
                return
            bounds_info: str = re.findall("\[(.*?)\]",bounds,re.I | re.M)[0]
            bounds_x = bounds_info.split(',')[0]
            bounds_y = bounds_info.split(',')[1]
            return int(bounds_x),int(bounds_y)
        else:
            return

    def clickElementByBounds(self,bounds_X,bounds_y,folder_path,bounds_md5,page_actrivity_name):
        # 点击坐标
        now = self.u.getStrfTime()
        try:
            if bounds_X and bounds_y:
                # 截图操作
                before_pic_name = f"{now}-{bounds_md5}-{bounds_X}-{bounds_y}-before.jpg"
                after_pic_name = f"{now}-{bounds_md5}-{bounds_X}-{bounds_y}-after.jpg"
                self.device.screenhot(filename=f"{folder_path}/{before_pic_name}")
                self.u.addPointToPic(pic_path=f"{folder_path}/{before_pic_name}",point=(bounds_X,bounds_y),save_name=before_pic_name,save_path=folder_path)
                self.device.click(x=bounds_X,y=bounds_y)
                self.device.screenhot(filename=f"{folder_path}/{after_pic_name}")

                # 获取点击后的 activity name
                activity_info = self.getActivityName()
                if activity_info:
                    now_activity_name = activity_info.get('activity')
                    if now_activity_name == page_actrivity_name:
                        # 仍在当前页面，不执行返回
                        pass
                    else:
                        # 记录新的 activity
                        self.new_activity.append(now_activity_name)
                        self.device.press('back')
        except Exception as e:
            raise e